// 路由鉴权
import router from "@/router";
import nprogerss from "nprogress";
import "nprogress/nprogress.css"; //进度条样式
import pinia from "./store";
import setting from "./setting";
import useUserStore from "@/store/modules/user";

nprogerss.configure({ showSpinner: false }); //进度条配置
let userStore = useUserStore(pinia);
//全局守卫

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  nprogerss.start();
  document.title = `${setting.title} - ${to.meta.title}`;
  let token = userStore.token;
  let usename = userStore.username;
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (usename) {
        next();
      } else {
        try {
          await userStore.userInfo();
          next();
        } catch (error) {
          console.log(error);
          //token失效
          //用户手动修改了本地信息
          //退出登录，跳转到/login
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
//全局后置守卫
router.afterEach((to, from) => {
  nprogerss.done();
});
